<!-- 用户管理 -->
<script setup lang="ts">
defineOptions({
  name: "User",
  inheritAttrs: false,
});

import {
  getCarUserPage,
  getUserForm,
  deleteUsers,
  updateCarUser,
  downloadTemplateAppApi,
  exportAppUser,
  importAppUser,
} from "@/api/user";
import { getDeptOptions } from "@/api/dept";
import { getRoleOptions } from "@/api/role";

import { UserForm, UserQuery, UserPageVO } from "@/api/user/types";
import type { UploadInstance } from "element-plus";
import { genFileId } from "element-plus";
import userTab from "../../tab/userTab.vue";

const queryFormRef = ref(ElForm); // 查询表单
const userFormRef = ref(ElForm); // 用户表单
const userFormUserRef = ref(ElForm); // 用户表单

const userInfoFormRef = ref(ElForm); // 用户表单
const uploadRef = ref<UploadInstance>(); // 上传组件

const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除用户ID集合 用于批量删除
const queryParams = reactive<UserQuery>({
  pageNum: 1,
  pageSize: 10,
  type: "2",
});
const dateTimeRange = ref("");
const total = ref(0); // 数据总数
const pageData = ref<UserPageVO[]>(); // 用户分页数据
const deptList = ref<OptionType[]>(); // 部门下拉数据源
const roleList = ref<OptionType[]>(); // 角色下拉数据源

watch(dateTimeRange, (newVal) => {
  if (newVal) {
    queryParams.startTime = newVal[0];
    queryParams.endTime = newVal[1];
  } else {
    queryParams.startTime = "";
    queryParams.endTime = "";
  }
});

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 800,
  title: "",
  types: "1",
});

// 弹窗对象
const dialogUser = reactive({
  visible: false,
  type: "user-form",
  width: "70%",
  height: "50%",
  title: "",
});

// 用户表单数据
const formData = reactive<UserForm>({
  status: 1,
  disableType: "0",
  loginName: "",
});

const formUserData = reactive<UserForm>({
  status: 1,
  disableType: "0",
});

// 用户导入数据
const importData = reactive({
  deptId: undefined,
  file: undefined,
  fileList: [],
});

// 校验规则
const rules = reactive({
  username: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  nickname: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
  deptId: [{ required: true, message: "所属部门不能为空", trigger: "blur" }],
  roleIds: [{ required: true, message: "用户角色不能为空", trigger: "blur" }],
  email: [
    {
      pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
  mobile: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getCarUserPage(queryParams)
    .then(({ data }) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  dateTimeRange.value = "";
  queryParams.pageNum = 1;
  queryParams.deptId = undefined;
  queryParams.startTime = undefined;
  queryParams.endTime = undefined;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}
/** 加载角色下拉数据源 */
async function loadRoleOptions() {
  getRoleOptions().then((response) => {
    roleList.value = response.data;
  });
}

/** 加载部门下拉数据源 */
async function loadDeptOptions() {
  getDeptOptions().then((response) => {
    deptList.value = response.data;
  });
}

/**
 * 打开弹窗
 *
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 * @param id 用户ID
 */
async function openDialog(type: string, row?: any, types?: any) {
  dialog.visible = true;
  dialog.type = type;
  dialog.types = types;
  // 用户表单弹窗
  await loadDeptOptions();
  await loadRoleOptions();
  if (row != undefined && row.userId != "") {
    if (types == "1") {
      dialog.title = "预览";
    } else {
      dialog.title = "禁用";
    }

    Object.assign(formData, { ...row });
  } else {
    dialog.title = "新增用户";
  }
}

async function showDialog(row?: any) {
  dialogUser.visible = true;

  if (row != undefined && row.userId != "") {
    dialog.title = "修改用户";
    Object.assign(formUserData, { ...row });
  } else {
    dialog.title = "新增用户";
  }
}

/**
 * 关闭弹窗
 *
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 */
function closeDialog() {
  dialog.visible = false;
  if (dialog.type === "user-form") {
    userFormRef.value.resetFields();
    userFormRef.value.clearValidate();

    formData.id = undefined;
    formData.status = 1;
  } else if (dialog.type === "user-import") {
    importData.file = undefined;
    importData.fileList = [];
  }
}

function closeUserDialog() {
  dialogUser.visible = false;
  userFormUserRef.value.resetFields();
  userFormUserRef.value.clearValidate();
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  if (dialog.type === "user-form") {
    userFormRef.value.validate((valid: any) => {
      if (valid) {
        const userId = formData.userId;
        loading.value = true;

        updateCarUser(formData)
          .then(() => {
            ElMessage.success("修改用户成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      }
    });
  } else if (dialog.type === "user-import") {
    if (!importData?.deptId) {
      ElMessage.warning("请选择部门");
      return false;
    }
    if (!importData?.file) {
      ElMessage.warning("上传Excel文件不能为空");
      return false;
    }
    importAppUser(importData?.deptId, importData?.file).then((response) => {
      ElMessage.success(response.data);
      closeDialog();
      resetQuery();
    });
  }
}, 3000);

/** 删除用户 */
function handleDelete(id?: number) {
  const userIds = [id || removeIds.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteUsers(userIds).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

/** Excel文件 Change */
function handleFileChange(file: any) {
  importData.file = file.raw;
}

/** Excel文件 Exceed  */
function handleFileExceed(files: any) {
  uploadRef.value!.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  uploadRef.value!.handleStart(file);
  importData.file = file;
}

/** 导出用户 */
function handleExport() {
  exportAppUser(queryParams).then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(
      response.headers["content-disposition"].split(";")[1].split("=")[1]
    );
    const fileType =
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

    const blob = new Blob([fileData], { type: fileType });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}
/** 下载导入模板 */
function downloadTemplate() {
  downloadTemplateAppApi().then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(
      response.headers["content-disposition"].split(";")[1].split("=")[1]
    );
    const fileType =
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

    const blob = new Blob([fileData], { type: fileType });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}

function handleSuccess(response: any, file: any, fileList: any) {
  ElMessage.success(response.data);
}

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 部门树
      <el-col :lg="4" :xs="24" class="mb-[12px]">
        <dept-tree v-model="queryParams.deptId" @node-click="handleQuery" />
      </el-col> -->

      <!-- 用户列表 -->
      <el-col :lg="24" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="关键字" prop="keywords">
              <el-input
                v-model="queryParams.keywords"
                placeholder="用户名/昵称/手机号"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="全部"
                clearable
                class="!w-[100px]"
              >
                <el-option label="启用" value="0" />
                <el-option label="注销" value="2" />
                <el-option label="禁用" value="3" />
              </el-select>
            </el-form-item>

            <el-form-item label="创建时间">
              <el-date-picker
                class="!w-[240px]"
                v-model="dateTimeRange"
                type="daterange"
                range-separator="~"
                start-placeholder="开始时间"
                end-placeholder="截止时间"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleQuery"
                ><i-ep-search />搜索</el-button
              >
              <el-button @click="resetQuery">
                <i-ep-refresh />
                重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never" class="table-container">
          <template #header>
            <div class="flex justify-between">
              <div>
                <!-- <el-button
                  v-hasPerm="['sys:user:add']"
                  type="success"
                  @click="openDialog('user-form')"
                  ><i-ep-plus />新增</el-button
                > -->
                <!-- <el-button
                  v-hasPerm="['sys:user:delete']"
                  type="danger"
                  :disabled="removeIds.length === 0"
                  @click="handleDelete()"
                  ><i-ep-delete />删除</el-button
                > -->
              </div>
              <div>
                <el-dropdown split-button>
                  导入
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="downloadTemplate">
                        <i-ep-download />下载模板</el-dropdown-item
                      >
                      <el-dropdown-item>
                        <i-ep-top />
                        <el-upload
                          ref="uploadRef"
                          style="height: 30px"
                          action="/dev-api/api/car/users/impAppUser"
                          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                          :limit="1"
                          :auto-upload="true"
                          :file-list="importData.fileList"
                          :on-change="handleFileChange"
                          :on-exceed="handleFileExceed"
                          :on-success="handleSuccess"
                        >
                          <div style="margin-top: 5px">导入数据</div>
                        </el-upload>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
                <el-button class="ml-3" @click="handleExport"
                  ><template #icon><i-ep-download /></template>导出</el-button
                >
              </div>
            </div>
          </template>

          <el-table
            v-loading="loading"
            :data="pageData"
            @selection-change="handleSelectionChange"
          >
            <!-- <el-table-column type="selection" width="50" align="center" /> -->
            <el-table-column
              align="center"
              label="序号"
              type="index"
              width="150"
            />

            <el-table-column
              label="用户ID"
              width="120"
              align="center"
              prop="userId"
            />

            <el-table-column
              label="车友号"
              width="120"
              align="center"
              prop="cc"
            />

            <el-table-column
              label="简介"
              width="120"
              align="center"
              :show-overflow-tooltip="true"
              prop="carDesc"
            />
            <el-table-column
              key="username"
              label="用户名"
              align="center"
              prop="loginName"
            >
              <template #default="scope">
                <el-link
                  :underline="false"
                  type="primary"
                  class="ml-5"
                  @click="showDialog(scope.row)"
                  >{{ scope.row.loginName }}
                </el-link>
              </template>
            </el-table-column>

            <el-table-column
              label="用户昵称"
              width="120"
              align="center"
              prop="nickName"
            />
            <el-table-column label="认证车辆" align="center">
              <template #default="scope">
                <span
                  v-for="(item, index) in scope.row.carAuthList"
                  :key="index"
                >
                  {{ item.brandName + " " + item.model }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              label="头像"
              align="center"
              prop="headImg"
              width="120"
            >
              <template #default="scope">
                <span
                  ><img :src="scope.row.headImg" style="height: 60px"
                /></span>
              </template>
            </el-table-column>

            <el-table-column label="性别" width="100" align="center" prop="sex">
              <template #default="scope">
                <span v-if="scope.row.sex == 0">男</span>
                <span v-if="scope.row.sex == 1">女</span>
              </template>
            </el-table-column>

            <el-table-column
              label="点赞量"
              width="120"
              align="center"
              prop="likeCount"
            />
            <el-table-column
              label="访问量"
              align="center"
              prop="visitsCount"
              width="120"
            />

            <el-table-column
              label="关注量"
              align="center"
              prop="followersCount"
              width="120"
            />

            <el-table-column
              label="状态"
              align="center"
              prop="status"
              width="120"
            >
              <template #default="scope">
                <span v-if="scope.row.status == 5"> 正常 </span>

                <span v-if="scope.row.status == 2"> 已注销 </span>

                <span v-if="scope.row.status == 6"> 禁用 </span>
              </template>
            </el-table-column>

            <el-table-column
              label="注册时间"
              align="center"
              prop="regDate"
              width="200"
            />

            <el-table-column
              label="IP地址"
              align="center"
              prop="ipAddr"
              width="120"
            />

            <el-table-column label="操作" align="center" prop="status">
              <template #default="scope">
                <el-button
                  v-if="scope.row.status == 0 || scope.row.status == 5"
                  v-hasPerm="['sys:user:edit']"
                  type="primary"
                  link
                  size="small"
                  @click="openDialog('user-form', scope.row)"
                  ><i-ep-edit />禁用</el-button
                >

                <el-button
                  v-if="scope.row.status == 6"
                  v-hasPerm="['sys:user:edit']"
                  type="primary"
                  link
                  size="small"
                  @click="openDialog('user-form', scope.row)"
                  ><i-ep-edit />解禁</el-button
                >
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click="openDialog('user-form', scope.row, 1)"
                  ><i-ep-view />查看</el-button
                >
              </template>
            </el-table-column>

            <!-- <el-table-column label="操作" fixed="right" width="220">
              <template #default="scope">
                <el-button
                  v-hasPerm="['sys:user:reset_pwd']"
                  type="primary"
                  size="small"
                  link
                  @click="resetPassword(scope.row)"
                  ><i-ep-refresh-left />重置密码</el-button
                >
                <el-button
                  v-hasPerm="['sys:user:edit']"
                  type="primary"
                  link
                  size="small"
                  @click="openDialog('user-form', scope.row.id)"
                  ><i-ep-edit />编辑</el-button
                >
                <el-button
                  v-hasPerm="['sys:user:delete']"
                  type="primary"
                  link
                  size="small"
                  @click="handleDelete(scope.row.id)"
                  ><i-ep-delete />删除</el-button
                >
              </template>
            </el-table-column> -->
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 用户详情 -->
    <el-dialog
      v-model="dialogUser.visible"
      :title="dialogUser.title"
      :width="dialogUser.width"
      height="800px"
      append-to-body
      @close="closeUserDialog"
    >
      <!-- 用户新增/编辑表单 -->
      <el-form
        ref="userFormUserRef"
        :model="formUserData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="loginName">
          <el-input
            v-model="formUserData.loginName"
            readonly
            placeholder="请输入用户名"
          />
        </el-form-item>

        <el-form-item label="用户昵称" prop="nickName">
          <el-input
            v-model="formUserData.nickName"
            readonly
            placeholder="请输入用户昵称"
          />
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-select
            v-model="formUserData.sex"
            placeholder="全部"
            clearable
            class="!w-[100px]"
          >
            <el-option label="男" value="0" />
            <el-option label="女" value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <userTab ref="userInfoTab" :userId="formUserData.userId"></userTab>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeUserDialog">返 回</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <!-- 用户新增/编辑表单 -->
      <el-form
        v-if="dialog.type === 'user-form'"
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="loginName">
          <el-input v-model="formData.loginName" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="formData.nickName" placeholder="请输入用户昵称" />
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-select
            v-model="formData.sex"
            placeholder="全部"
            clearable
            class="!w-[100px]"
          >
            <el-option label="男" value="0" />
            <el-option label="女" value="1" />
          </el-select>
        </el-form-item>

        <el-form-item label="禁用类型">
          <el-select
            v-model="formData.disableType"
            placeholder="全部"
            clearable
            class="!w-[100px]"
          >
            <el-option label="永久" value="0" />
            <el-option label="临时" value="1" />
          </el-select>
        </el-form-item>

        <el-form-item label="禁用时间" v-if="formData.disableType == '1'">
          <el-date-picker
            class="!w-[240px]"
            v-model="dateTimeRange"
            type="daterange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="截止时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.disabledVal">
            <el-radio :label="1">解禁</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="handleSubmit"
            v-if="dialog.types != '1'"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
